import java.util.concurrent.CountDownLatch;

/**
 * 5 静态内部类实现单例模式
 * 这种方法是饿汉式的一种升级，这种方式同样利用了classloder的机制来保证初始化instance时只有一个线程，同时实现了延时加载
 *
 * @author agstar
 * @date 2019/7/3 10:50
 */
public class StaticInnerClass {

    private static class InstanceHolder {
        private static final StaticInnerClass instance = new StaticInnerClass();
    }

    /**
     * 构造函数私有化
     */
    private StaticInnerClass() {
        if (InstanceHolder.instance != null) {
            throw new RuntimeException("单例构造器禁止反射!");
        }
    }

    /**
     * 提供一个全局的静态方法
     */
    public static StaticInnerClass getInstance() {
        return InstanceHolder.instance;
    }

    public static void main(String[] args) {
        int count = 2000;
        CountDownLatch latch = new CountDownLatch(count);

        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                StaticInnerClass instance = StaticInnerClass.getInstance();
                System.out.println(instance);
            }).start();
            latch.countDown();
        }
    }

}
